package com.wry.service.impl;

import com.wry.entity.WStock;
import com.wry.service.StockApiService;
import com.wry.service.WStockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <h1>  <h1>
 *
 * @author 魏如元
 * @since 2022/10/14
 */
@Service
@Slf4j
public class StockApiServiceImpl implements StockApiService {

    @Resource
    private WStockService stockService;
    @Resource
    private RedissonClient redissonClient;

    private static final String KEY = "stock:deduction:key";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductionStock(Integer buyNum, Integer goodId) {
        final RLock lock = redissonClient.getLock(KEY);
        try {
            log.info("线程：{} 拿到锁了",Thread.currentThread().getName());
            if (lock.tryLock(500, 30, TimeUnit.MILLISECONDS)){
                final WStock stock = stockService.getById(goodId);
                if (Objects.isNull(stock)){
                    log.warn("goodsId = {}，not found",goodId);
                    throw new RuntimeException("goodsId = "+goodId+" not found ！");
                }

                int num = stock.getNum() - buyNum;

                if (num < 0){
                    log.warn("goodsId = {}，库存不足！",goodId);
                    throw new RuntimeException("库存不足！");
                }

                stockService.lambdaUpdate()
                        .eq(WStock::getId,goodId)
                        .set(WStock::getNum,num)
                        .update();
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("goodsId = {}, 扣减库存时发生未知异常：{}",goodId, e.getMessage());
        }finally {
            log.info("线程：{} 即将释放锁",Thread.currentThread().getName());
            lock.unlock();
        }
    }
}
